import { safeIndexApi } from '@/api';
import { Form, Input, message, Select, Spin } from 'antd';
import { forwardRef, useCallback, useEffect, useImperativeHandle, useState } from 'react';
import Ostyle from './index.less';
import { IFactorFormProps, TFactorRef } from './interface';

const rules = (text: string) => {
  return [{ required: true, message: `${text}` }];
};

const AddOrEditFactorForm = forwardRef<TFactorRef, IFactorFormProps>((props, ref) => {
  const { pageType } = props; // 1车辆相关  2司机相关  3驾驶行为
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(true);
  const { type, factorId, factorName, groupId, code, calculationRules, remarks } = props;
  const [matterList, setMatterList] = useState<any[]>([]);
  const [codeList, setCodeList] = useState<any[]>([]);
  const [isEdit, setIsEdit] = useState<boolean>(false);
  const onSubmit = () => {
    return form
      .validateFields()
      .then((val) => {
        const finalValues = { ...val, type, relatedType: pageType };
        if (type === 'edit') {
          finalValues.factorId = factorId;
        }
        return Promise.resolve(finalValues);
      })
      .catch((err) => {
        // message.error(' AddOrEditFactorForm ERR ');
        // return Promise.reject(err); // 这东西会报错UNcaught (in promise) {values: {…}, errorFields: Array(1), outOfDate: false}
        return console.log(JSON.stringify(err));
      });
  };
  // 获取事项列表
  const getMatterList = useCallback(() => {
    return new Promise((resolve, reject) => {
      safeIndexApi
        .getMatterGropList({ relatedType: pageType })
        .then((res: any) => {
          if (res.code == 200) {
            const list = res.data.map((el: any) => {
              return { value: el.groupId, label: el.groupName };
            });
            setMatterList(list);
            if (type === 'edit' && factorId) form.setFieldsValue({ groupId });
            resolve('suc');
          } else reject('err');
        })
        .catch((err) => {
          reject(err);
        });
    });
  }, [factorId, form, groupId, type]);
  // 获取编号列表
  const getCodeList = useCallback(() => {
    return new Promise((resolve, reject) => {
      safeIndexApi
        .getFactorCodeList({ relatedType: pageType })
        .then((res: any) => {
          if (res.code == 200) {
            const list = res.data.map((el: any) => {
              return { value: el.code, label: el.code + '（' + el.desc + '）' };
            });
            setCodeList(list);
            if (type === 'edit' && factorId) form.setFieldsValue({ code });
            resolve('suc');
          } else reject('err');
        })
        .catch((err) => {
          reject(err);
        });
    });
  }, [code, factorId, form, type]);
  const lationRulesList = [
    {
      value: 1,
      label: '按简单规则计算',
    },
    {
      value: 2,
      label: '按公式A计算',
    },
    {
      value: 3,
      label: '按公式B计算',
    },
    {
      value: 4,
      label: '按公式C计算',
    },
  ];
  useEffect(() => {
    if (type === 'edit' && factorId) {
      form.setFieldsValue({ factorName });
      form.setFieldsValue({ calculationRules });
      form.setFieldsValue({ remarks });
      setIsEdit(true);
    } else {
      form.setFieldsValue({ calculationRules: 1 });
    }

    Promise.all([getMatterList(), getCodeList()])
      .then((res) => {
        if (res[0] === 'suc' && res[1] === 'suc') {
          setLoading(false);
        }
      })
      .catch(() => {
        message.error('获取信息失败');
        setLoading(false);
      });
  }, [calculationRules, factorId, factorName, form, getCodeList, getMatterList, remarks, type]);

  useImperativeHandle(ref, () => ({
    onSubmit,
  }));

  return (
    <Spin spinning={loading} style={{ padding: '16px 16px 0' }}>
      <Form layout="horizontal" form={form} labelCol={{ span: 6 }} wrapperCol={{ span: 18 }} labelAlign="left">
        <Form.Item className={Ostyle.formItem} name="groupId" label="因子所属事项" rules={rules('请选择因子所属事项')}>
          <Select placeholder="请选择" options={matterList} />
        </Form.Item>
        <Form.Item
          className={Ostyle.formItem}
          name="factorName"
          label="影响因子名称"
          rules={rules('请输入30字以内因子名称')}
        >
          <Input maxLength={30} placeholder="请输入" />
        </Form.Item>

        <Form.Item className={Ostyle.formItem} name="code" label="影响因子编号" rules={rules('请选择影响因子编号')}>
          <Select placeholder="请选择" disabled={isEdit} options={codeList} />
        </Form.Item>
        <Form.Item
          className={Ostyle.formItem}
          name="calculationRules"
          label={
            <span>
              计算规则
              <a
                style={{ marginLeft: 5 }}
                href="http://prototype.scm.logibeat.com/instructions/formula.html"
                target="_blank"
                rel="noreferrer"
              >
                (说明)
              </a>
            </span>
          }
          rules={rules('请选择计算规则')}
        >
          <Select placeholder="请选择" options={lationRulesList} />
        </Form.Item>
        <Form.Item name="remarks" label={<span style={{ marginLeft: 12 }}>备注</span>}>
          <Input.TextArea placeholder="" autoSize={{ minRows: 3, maxRows: 5 }} maxLength={200} />
        </Form.Item>
      </Form>
    </Spin>
  );
});

export default AddOrEditFactorForm;
